import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { SDBody, SDLoading } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'

import GoodsItem from '../../../comps/goods-item'
import SKUPicker from '../../../comps/sku-picker'
import CommonEmptyView from '../../../comps/empty-view'

import EmptyIcon from '../../../images/ic_nothing_search.png'


import './index.less'

type PageState = {
  mainIsLoading: boolean,
  dataList: any[],                        // 商品数据列表
  loading: boolean,                       // 是否正在加载中
  hasData: boolean,                       // 是否有商品数据
  hasMore: boolean,                       // 是否有更多数据
  hideLoading: boolean,                   // 强制隐藏loading
}

type PageOwnProps = {}

interface GoodsListPage {
  props: PageProps & PageOwnProps
}

const navigationBarTitleMap = {
  news: '最新上架',
  recommend: '推荐产品'
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class GoodsListPage extends Component<PageOwnProps, PageState> {

  constructor () {
    super()
    this.state = {
      mainIsLoading: true,
      dataList: [],
      loading: false,
      hasData: true,
      hasMore: true,
      hideLoading: false
    }
  }


  componentDidMount () {
    let comeFrom = (this.$router.params || {}).comeFrom || ''
    let title = navigationBarTitleMap[comeFrom] || '商品列表'
    Taro.setNavigationBarTitle({
      title: title
    })

    this.fetchData(0, true)
  }

  onPullDownRefresh () {
    this.fetchData(0)
  }

  onReachBottom () {
    const { dataList } = this.state
    this.fetchData(dataList.length)
  }

  fetchData = async (offset: number = 0, resetData: boolean = false) => {
    const limit = 6
    let { loading, hasData, hasMore, dataList } = this.state
    if (loading || (offset > 0 && !hasMore)) { return }
    if (offset == 0) {
      dataList = []
    }
    let pageState: any = {
      loading: true,
      hasMore: true,
      hasData: true,
      hideLoading: resetData
    }
    if (resetData) {
      pageState.dataList = dataList
    }

    await this.setState({...pageState})

    try {
      const resp = await SDUtils.doGet('/wxmini/traderProduct', {
        offset: offset,
        limit: limit,
        traderId: '1'
      })
      dataList = dataList.concat(resp.items ||[])
      hasData = resp.total > 0
      hasMore = resp.total > dataList.length
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      Taro.stopPullDownRefresh()
      this.setState({
        mainIsLoading: false,
        loading: loading,
        hasMore: hasMore,
        hasData: hasData,
        dataList: dataList
      })
    }
  }

  render () {
    const { mainIsLoading, dataList, hasData, hasMore, hideLoading, loading } = this.state
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className="cell-list-pic">
          {
            dataList.map((item, index) => {
              return (
                <View className="cell-arrange-pic" key={index}>
                  <GoodsItem
                    extData={index}
                    width={336}
                    height={550}
                    imgUrl={item.coverImage || ''}
                    title={item.name}
                    price={SDUtils.formatPrice(`${item.minPrice}`)}
                    showTagPrice={true}
                    tagPrice={SDUtils.formatPrice(`${item.minTagPrice}`)}
                    showCartNum={false}
                    cartNum={0}
                    showSalesVolume={true}
                    salesVolume={item.salesVolume || 0}
                    showCartIcon={true}
                    bgColor='#fff'
                    onClick={this.gotoGoodsDetail}
                    onCartClick={this.onCartIconTaped}
                  />
                </View>
              )
            })
          }
        </View>

        <SDLoading loading={loading} hasData={hasData} hasMore={hasMore} hideLoading={hideLoading}>
          <CommonEmptyView title='暂无数据' icon={EmptyIcon} />
        </SDLoading>

        <SKUPicker ref='compsSkuPicker' onSelect={this.onSkuSelect}/>
      </SDBody>
    )
  }

  onSkuSelect = () => {
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.dismiss()
  }

  onCartIconTaped = (index: number, e) => {
    e.stopPropagation && e.stopPropagation()
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.show(productId)
  }

  gotoGoodsDetail = (index: number) => {
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    SDUtils.jumpTo('/pages/goods/detail/index', { productId: productId})
  }
}

export default GoodsListPage as ComponentClass<PageOwnProps, PageState>
